package com.htkj.demo.okhttp;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.htkj.demo.bean.DeviceData;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ResultCallback<T> implements Callback {
    private Handler mHandler = null;
    private ResponseListener<T> listener;
    private Type type; // 保存泛型类型信息

    // 构造函数需传入TypeToken，用于获取泛型具体类型
    public ResultCallback(ResponseListener<T> listener, TypeToken<T> typeToken) {
        this.listener  = listener;
        this.type  = typeToken.getType();  // 提取泛型类型（如DeviceData.class ）
        mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String result = response.body().string();
        try {
            // 使用Gson解析完整响应（先获取外层JSON对象）
            Gson gson = new Gson();
            BaseResponse baseResponse = gson.fromJson(result,  BaseResponse.class);

            if (baseResponse.code  == 200) {
                // 解析内层data字段为泛型对象T
                String dataJson = gson.toJson(baseResponse.data);  // 将data转为JSON字符串
                T resultS1 = gson.fromJson(dataJson,  type); // 使用保存的泛型类型解析
                sendSuccessCallback(call, resultS1);
            } else {
                sendFailureCallback(call, new IOException(baseResponse.msg));
            }

        } catch (Exception e) {
            sendFailureCallback(call, new IOException("JSON解析失败: " + e.getMessage()));
        }
    }

    @Override
    public void onFailure(Call call, IOException e) {
        sendFailureCallback(call, e);
    }

    private void sendFailureCallback(Call call, final IOException e) {
        mHandler.post(()  -> listener.onFailure(e.getMessage()));
    }

    private void sendSuccessCallback(Call call, final T result) {
        Log.e("http", "${1}" + result.toString());
        Log.e("http", "${2}" + (result instanceof DeviceData));
        Log.e("http", "${2}" + result.getClass().getName());
        mHandler.post(()  -> listener.onSuccess(result));
    }

    // 辅助类：解析外层JSON结构（code/msg/data）
    private static class BaseResponse {
        int code;
        String msg;
        Object data; // 临时用Object接收，后续再解析为泛型T
    }
}